import LayerBase, { getLayerId } from "@/core/layers/base"
import { CanvasContextType } from "../public"


type Options = {
  name: string
  ctxType: CanvasContextType
  x?: number
  y?: number
}

export default class LayerFPS extends LayerBase {
  id = getLayerId()
  name
  ctxType
  readonly layerType = 'fps'

  x: number
  y: number
  value: number = 0
  lastCounter: number = 0
  lastTimestamp: number = 0
  visible = false

  constructor(options: Options){
    super()
    this.name = options.name
    this.ctxType = options.ctxType
    this.x = options.x !== undefined ? options.x : 0
    this.y = options.y !== undefined ? options.y : 0
  }

  render(ctx: CanvasRenderingContext2D){
    const timestamp = Date.now();
    this.lastCounter++
    if(timestamp - this.lastTimestamp > 1000){
      this.value = this.lastCounter
      this.lastCounter = 0;
      this.lastTimestamp = timestamp
    }

    ctx.globalAlpha = this.opacity
    ctx.font = '13px Arial'
    ctx.fillStyle = '#fff'
    ctx.fillText(`FPS ${this.value}`, this.x, this.y)
    ctx.strokeStyle = '#000'
    ctx.lineWidth = 0.4
    ctx.strokeText(`FPS ${this.value}`, this.x, this.y)
    return true
  }

  serialize(){
    return {
      id: this.id,
      name: this.name,
      ctxType: this.ctxType,
      layerType: this.layerType,
      x: this.x,
      y: this.y,
      opacity: this.opacity,
      visible: this.visible,
    }
  }
}